package Offer.offer;

import domain.ListNode;

/**
 * 反转链表
 * @author leiwenkang
 * @date 2020/4/6
 */
public class Test16反转链表 {
    public static void main(String[] args) {
        ListNode p1 = new ListNode(1);
        ListNode p2 = new ListNode(2);
        ListNode p3 = new ListNode(3);
        ListNode p4 = new ListNode(4);
        p1.next=p2;
        p2.next=p3;
        p3.next=p4;
        p4.next=null;
        System.out.println(reverseListNode(p1).val);
    }

    public static ListNode reverseListNode2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode p = head;
        ListNode pre = null;
        while (p != null) {
            ListNode next = p.next;
            p.next = pre;
            pre = p;
            p = next;
        }
        return pre;
    }



    public static ListNode reverseListNode(ListNode head) {
        ListNode p = head;
        ListNode pre = null;
        while (p != null) {
            ListNode next = p.next;
            p.next = pre;
            pre = p;
            p = next;
        }
        return pre;
    }
}
